package com.panopset.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import com.panopset.Logger;
import com.panopset.compat.Logz;
import com.panopset.sf.Pan;

/**
 * File backed properties.
 * @author Karl Dinwiddie.
 *
 */
public final class FileProps implements Pan {

    /**
     * @param key Key.
     * @return Value.
     */
    public String get(final String key) {
        return getProps().getProperty(key);
    }

    /**
     * @param key Key.
     * @param value Value.
     */
    public void put(final String key, final String value) {
        getProps().setProperty(key, value);
    }

    /**
     * Create any needed parent directories, save the file.
     */
    public void flush() {
        if (!f.exists()) {
            f.getParentFile().mkdirs();
            try {
				f.createNewFile();
			} catch (IOException e) {
				Logz.dspmsg("Could not create " + 
				new Filez().getCanonicalPath(f));
				Logger.log(e);
				return;
			}
        }
        try {
        	FileOutputStream fos = new FileOutputStream(f);
            getProps().store(fos, "");
            fos.flush();
            fos.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Properties file.
     */
    private File f;

    /**
     *
     * @return File.
     */
    public File getFile() {
        return f;
    }

    public void setFile(final File file) {
    	f = file;
    }
    /**
     *
     * @param file Properties file.
     */
    public FileProps(final File file) {
        f = file;
        if (!new Filez().isAvailable(file)) {
            throw new RuntimeException(new Filez().getCanonicalPath(file));
        }
    }

    /**
     * Properties.
     */
    private Properties props;

    /**
     *
     * @return Properties.
     */
    private Properties getProps() {
        if (props == null) {
            props = new Properties();
            try {
                props.load(new FileInputStream(f));
            } catch (Exception e) {
                Logger.log(e);
            }
            return props;
        }
        return props;
    }
}
